import { faker } from '@faker-js/faker/locale/zh_CN';

import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess } from '~/utils/response';

interface StaffItem {
  account: string;
  department: string;
  email: string;
  enabled: boolean;
  entryTime: string;
  id: string;
  name: string;
  phone: string;
  role: string;
}

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function generateMockDataList(count: number): StaffItem[] {
  return Array.from({ length: count }, (_, i) => ({
    account: faker.internet.username(),
    department: faker.helpers.arrayElement([
      '技术部',
      '产品部',
      '运营部',
      '市场部',
      '人事部',
      '财务部',
    ]),
    email: faker.internet.email(),
    enabled: faker.datatype.boolean(),
    entryTime: formatDate(faker.date.past()),
    id: (i + 1).toString(),
    name: faker.person.fullName(),
    phone: faker.phone.number('1##########'),
    role: faker.helpers.arrayElement([
      '管理员',
      '普通用户',
      '审核员',
      '操作员',
    ]),
  }));
}

const mockData = generateMockDataList(100);

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  const { method } = event;
  const query = getQuery(event);

  if (method === 'GET') {
    const page = Number(query.page) || 1;
    const pageSize = Number(query.pageSize) || 20;

    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const list = mockData.slice(startIndex, endIndex);

    return useResponseSuccess({
      list,
      page,
      pageSize,
      total: mockData.length,
    });
  }

  if (method === 'POST') {
    return useResponseSuccess({ message: '职员创建成功' });
  }

  if (method === 'PUT') {
    return useResponseSuccess({ message: '职员更新成功' });
  }

  if (method === 'DELETE') {
    return useResponseSuccess({ message: '职员删除成功' });
  }

  throw createError({
    statusCode: 405,
    statusMessage: 'Method not allowed',
  });
});